﻿/*******************************************************************************
Copyright (c) 2011-2013, PKStudio
Copyright (c) 2008-2010, Valentin Milea

http://pkstudio.org

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*******************************************************************************/

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace PKEngine
{
	/// <summary>
	/// Singleton that handles all the mouse events.
	/// The dispatcher dispatches events to the registered MouseHandlers.
	/// </summary>
	public class PKMouseDispatcher
	{
		#region PKMouseEventType
		private enum PKMouseEventType
		{
			MouseDown,
			MouseDrag,
			MouseUp,
			MouseMove,
			MouseMax
		}
		#endregion

		#region Singleton
		private static PKMouseDispatcher _sharedDispatcher;

		public static PKMouseDispatcher SharedDispatcher
		{
			get
			{
				if (_sharedDispatcher == null)
				{
					_sharedDispatcher = new PKMouseDispatcher();
				}
				return _sharedDispatcher;
			}
		}
		#endregion

		#region Private Fields
		List<PKMouseHandler> mouseHandlers;
		bool locked;
		bool toAdd;
		List<PKMouseHandler> handlersToAdd;
		bool toRemove;
		List<IPKMouseResponder> respondersToRemove;
		bool toClear;
		#endregion

		#region Public Properties
		/// <summary>
		/// Whether or not the events are going to be dispatched.
		/// <remarks>Default value is true</remarks>
		/// </summary>
		public bool DispatchEvents { get; set; }
		#endregion

		#region Initialization
		private PKMouseDispatcher()
		{
			this.DispatchEvents = true;

			this.mouseHandlers = new List<PKMouseHandler>();
			this.handlersToAdd = new List<PKMouseHandler>();
			this.respondersToRemove = new List<IPKMouseResponder>();

			this.locked = false;
			this.toAdd = false;
			this.toRemove = false;
			this.toClear = false;
		}
		#endregion

		#region Public Methods
		/// <summary>
		/// Adds a mouse handler to the dispatcher's list.
		/// </summary>
		/// <param name="target">target object</param>
		/// <param name="priority">priority of handler</param>
		/// <param name="swallowesEvents">whether or not the event is swallowed</param>
		public void AddHandler(IPKMouseResponder target, int priority, bool swallowesEvents)
		{
			Debug.Assert(target != null, "PKMouseDispatcher.AddHandler: Argument cannot be null.");

			PKMouseHandler handler = new PKMouseHandler(target, priority, swallowesEvents);
			if (!this.locked)
			{
				this.ForceAddHandler(handler);
			}
			else
			{
				if (!RemoveResponderFromList(target, respondersToRemove))
				{
					this.handlersToAdd.Add(handler);
					this.toAdd = true;
				}
			}
		}

		/// <summary>
		/// Removes a mouse handler.
		/// </summary>
		/// <param name="target">target object</param>
		public void RemoveHandler(IPKMouseResponder target)
		{
			if (target == null)
			{
				return;
			}

			if (!this.locked)
			{
				this.ForceRemoveHandler(target);
			}
			else
			{
				if (!RemoveHanderFromList(target, handlersToAdd))
				{
					this.respondersToRemove.Add(target);
					this.toRemove = true;
				}
			}
		}

		/// <summary>
		/// Removes all mouse handlers.
		/// </summary>
		public void ClearHandlers()
		{
			if (!this.locked)
			{
				this.ForceClearHandlers();
			}
			else
			{
				this.toClear = true;
			}
		}

		/// <summary>
		/// Changes the priority of a previously added mouse handler.
		/// The lower number, the higher priority.
		/// </summary>
		/// <param name="target">target object</param>
		/// <param name="priority">priority of handler</param>
		public void SetPriority(IPKMouseResponder target, int priority)
		{
			Debug.Assert(target != null, "PKMouseDispatcher.SetPriority: Argument cannot be null.");

			PKMouseHandler handler = this.FindHandler(target);

			Debug.Assert(handler != null, "PKMouseDispatcher.SetPriority: Cannot find specified mouse handler.");

			handler.Priority = priority;
			this.SortHandlers();
		}

		/// <summary>
		/// Mouse Down event.
		/// </summary>
		/// <param name="mouse">the mouse</param>
		public void MouseDown(PKMouseEvent mouse)
		{
			if (this.DispatchEvents)
			{
				this.DispatchEvent(mouse, PKMouseEventType.MouseDown);
			}
		}

		/// <summary>
		/// Mouse drag event.
		/// </summary>
		/// <param name="mouse">the mouse</param>
		public void MouseDrag(PKMouseEvent mouse)
		{
			if (this.DispatchEvents)
			{
				this.DispatchEvent(mouse, PKMouseEventType.MouseDrag);
			}
		}

		/// <summary>
		/// Mouse up event.
		/// </summary>
		/// <param name="mouse">the mouse</param>
		public void MouseUp(PKMouseEvent mouse)
		{
			if (this.DispatchEvents)
			{
				this.DispatchEvent(mouse, PKMouseEventType.MouseUp);
			}
		}

		/// <summary>
		/// Mouse move event.
		/// </summary>
		/// <param name="mouse">the mouse</param>
		public void MouseMove(PKMouseEvent mouse)
		{
			if (this.DispatchEvents)
			{
				this.DispatchEvent(mouse, PKMouseEventType.MouseMove);
			}
		}
		#endregion

		#region Private Methods
		private static bool RemoveResponderFromList(IPKMouseResponder responder, List<IPKMouseResponder> list)
		{
			foreach (IPKMouseResponder item in list)
			{
				if (list == responder)
				{
					list.Remove(item);
					return true;
				}
			}
			return false;
		}

		private static bool RemoveHanderFromList(IPKMouseResponder responder, List<PKMouseHandler> list)
		{
			foreach (PKMouseHandler item in list)
			{
				if (item.Target == responder)
				{
					list.Remove(item);
					return true;
				}
			}
			return false;
		}

		private void ForceAddHandler(PKMouseHandler handler)
		{
			int index = 0;
			foreach (PKMouseHandler item in this.mouseHandlers)
			{
				if (item.Priority < handler.Priority)
				{
					index++;
				}
				Debug.Assert(item.Target != handler.Target, "PKMouseDispatcher.AddHandler: Handler already added to mouse dispatcher.");
			}
			this.mouseHandlers.Insert(index, handler);
		}

		private void ForceRemoveHandler(IPKMouseResponder target)
		{
			foreach (PKMouseHandler item in this.mouseHandlers)
			{
				if (item.Target == target)
				{
					this.mouseHandlers.Remove(item);
					break;
				}
			}
		}

		private void ForceClearHandlers()
		{
			this.mouseHandlers.Clear();
		}

		private PKMouseHandler FindHandler(IPKMouseResponder target)
		{
			foreach (PKMouseHandler item in this.mouseHandlers)
			{
				if (item.Target == target)
				{
					return item;
				}
			}
			if (toAdd)
			{
				foreach (PKMouseHandler item in this.handlersToAdd)
				{
					if (item.Target == target)
					{
						return item;
					}
				}
			}
			return null;
		}

		private void SortHandlers()
		{
			this.mouseHandlers.Sort(
				delegate(PKMouseHandler item1, PKMouseHandler item2)
				{
					return item1.Priority.CompareTo(item2.Priority);
				});
		}

		private void DispatchEvent(PKMouseEvent mouse, PKMouseEventType type)
		{
			Debug.Assert(type < PKMouseEventType.MouseMax, "PKMouseDispatcher.DispatchEvent: Invalid mouse event.");

			locked = true;

			if (mouseHandlers.Count > 0)
			{
				foreach (PKMouseHandler handler in mouseHandlers)
				{
					bool claimed = false;
					if (type == PKMouseEventType.MouseDown)
					{
						claimed = handler.Target.MouseDown(mouse);
						if (claimed)
						{
							handler.ClaimedEvents = mouse;
						}
					}
					else if (handler.ClaimedEvents == mouse)
					{
						claimed = true;
						if (type == PKMouseEventType.MouseDrag)
						{
							handler.Target.MouseDrag(mouse);
						}
						else if (type == PKMouseEventType.MouseUp)
						{
							handler.Target.MouseUp(mouse);
							handler.ClaimedEvents = null;
						}
					}
					if (claimed && handler.SwallowesEvents)
					{
						// Then other handlers cannot receive this mouse event.
						break;
					}
				}

				foreach (PKMouseHandler handler in mouseHandlers)
				{
					if (type == PKMouseEventType.MouseMove)
					{
						if (handler.Target.MouseMove(mouse) && handler.SwallowesEvents)
						{
							// Then other handlers cannot receive this mouse event.
							break;
						}
					}
				}
			}

			locked = false;
			if (toRemove)
			{
				toRemove = false;
				foreach (IPKMouseResponder item in respondersToRemove)
				{
					this.ForceRemoveHandler(item);
				}
				respondersToRemove.Clear();
			}
			if (toAdd)
			{
				toAdd = false;
				foreach (PKMouseHandler item in handlersToAdd)
				{
					this.ForceAddHandler(item);
				}
				handlersToAdd.Clear();
			}
			if (toClear)
			{
				toClear = false;
				this.ForceClearHandlers();
			}

		}
		#endregion
	}
}
